//
// Created by subject on 2025/5/16.
//

#include "JavaVMHelper.h"
#include "LogUtils.h"

JavaVMHelper &JavaVMHelper::getInstance() {
    static JavaVMHelper instance; // 单例模式
    return instance;
}

void JavaVMHelper::setJavaVm(JavaVM *javaVM) {
    vm_.store(javaVM, std::memory_order_release);
    LOGI("JavaVM set successfully.");
}

JNIEnv *JavaVMHelper::getJniEnv() {
    JavaVM* vm = vm_.load(std::memory_order_acquire);
    if (!vm) return nullptr;

    JNIEnv* env = nullptr;
    jint status = vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6);

    if (status == JNI_EDETACHED) {
        std::lock_guard<std::mutex> lock(mutex_);
        if (vm->AttachCurrentThread(&env, nullptr) == JNI_OK) {
            attachedThreads_.insert(std::this_thread::get_id());
        } else {
            env = nullptr;
        }
    }
    return env;
}

void JavaVMHelper::detachCurrentThread() {
    JavaVM* vm = vm_.load(std::memory_order_acquire);
    if (!vm) return;

    std::lock_guard<std::mutex> lock(mutex_);
    if (attachedThreads_.erase(std::this_thread::get_id()) > 0) {
        vm->DetachCurrentThread();
    }
}

